package com.sduept.i1.model;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

// 在那种消息未得到确认需要补包的场景，可能会用到这个类
public class ClientManagement {
	private int clearCount; // 累积计数，到达一定次数之后清空一下未使用的
	
	private Map<String, ResponseState> map;
	
	public ClientManagement() {
		this.clearCount = 0;
		this.map = new HashMap<String, ResponseState>();
	}
	
	// 创建新的响应状态
	public void newConnection(String deviceId) {
		if(map.containsKey(deviceId)) {
			map.replace(deviceId, new ResponseState());
		} else {
			map.put(deviceId, new ResponseState());
		}
		
		clear();
	}
	
	// 查看请求是否得到响应
	public boolean checkResponse(String deviceId) {
		ResponseState r = map.get(deviceId);
		if(r != null && r.isResponse) {
			clear();
			return true;
		}
		
		clear();
		return false;
	}
	
	// 对得到响应的请求进行标记
	public void setResponse(String deviceId) {
		ResponseState r = map.get(deviceId);
		if(r != null) {
			r.isResponse = true;
		}
	}
	
	// 清除掉 map 中存留时间超过 20s 的对象
	private void clear() {
		this.clearCount++;
		if(clearCount > 10) {
			long abandonTime = System.currentTimeMillis() - 20000;
			Set<String> idSet = map.keySet();
			for(String id: idSet) {
				if(map.get(id).timeStamp < abandonTime) {
					map.remove(id);
				}
			}
		}
	}
	
	public class ResponseState {
		private boolean isResponse;
		private long timeStamp;
		
		private ResponseState() {
			this.isResponse = false;
			this.timeStamp = System.currentTimeMillis();
		}
		
	}
}
